package com.stox.shared.core.model.enumeration;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.stox.shared.core.i18n.MessageSource;

public enum Span {
	DAY_1("DAY_1", Calendar.DATE, 1),
	WEEK_1("WEEK_1", Calendar.WEEK_OF_YEAR, 1),
	MONTH_1("MONTH_1", Calendar.MONTH, 1),
	QUARTER_1("QUARTER_1", Calendar.MONTH, 3),
	YEAR_1("YEAR_1", Calendar.YEAR, 1),
	YEAR_2("YEAR_2", Calendar.YEAR, 2),
	YEAR_3("YEAR_3", Calendar.YEAR, 3),
	MAX("MAX", Calendar.YEAR, 999);

	private final int unit;
	private final int count;
	private final String key;

	private Span(final String key, final int unit, final int count) {
		this.unit = unit;
		this.count = count;
		this.key = key;
	}

	public int getCount() {
		return count;
	}

	public String getKey() {
		return key;
	}

	public int getUnit() {
		return unit;
	}

	@Override
	public String toString() {
		return MessageSource.get(key);
	}

	/**
	 * Cached instance to improve performance
	 */
	private static Calendar calendar = Calendar.getInstance();

	public Date add(final Date date, final int count) {
		synchronized (calendar) {
			calendar.setTime(date);
			add(calendar, count);
			return calendar.getTime();
		}
	}

	public void add(final Calendar calendar, final int count) {
		calendar.add(unit, count * this.count);
	}

	public List<BarSpan> getBarSpans() {
		final List<BarSpan> barSpans = new ArrayList<BarSpan>();
		for (final BarSpan barSpan : BarSpan.values()) {
			if (barSpan.getUnit() > getUnit()) {
				/*
				 * if (ordinal() >= QUARTER_1.ordinal() && barSpan.ordinal() <= BarSpan.HOURLY.ordinal()) { continue; }
				 */
				barSpans.add(barSpan);
			}
		}
		return barSpans;
	}
}
